namespace soccer.helper {

    export class PhyTap extends PhyObject {
        private limitX: number
        private limitY: number
        private limitWidth: number
        private limitHeight: number
        protected _needUpdate: boolean = false
        protected _moveStep: number
        protected _tmpVelcity: Box2D.Common.Math.b2Vec2

        constructor(type: PhyObjectType, body: Box2D.Dynamics.b2Body, limitX, limitY, limitWidth, limitHeight: number) {
            super(type, body)
            this.limitX = limitX / helper.p2m
            this.limitY = limitY / helper.p2m
            this.limitWidth = limitWidth / helper.p2m
            this.limitHeight = limitHeight / helper.p2m
        }

        public set targetPos(pos: Box2D.Common.Math.b2Vec2) {
            if (pos.x < this.limitX) {
                pos.x = this.limitX
            }
            if (pos.x > this.limitX + this.limitWidth) {
                pos.x = this.limitX + this.limitWidth
            }
            if (pos.y < this.limitY) {
                pos.y = this.limitY
            }
            if (pos.y > this.limitY + this.limitHeight) {
                pos.y = this.limitY + this.limitHeight
            }
            if (!this._targetPos || (this._targetPos.x != pos.x) || (this._targetPos.y != pos.y)) {
                this._needUpdate = true
                this._tmpVelcity = null
                this._targetPos = pos
            }
        }

        public beforeStep() {
            if (this._needUpdate) {
                {
                    let v = Subtract(this._targetPos, this.body.GetPosition())
                    v.x = v.x * helper.step * 1.2
                    v.y = v.y * helper.step * 1.2
                    if (v.x == 0 && v.y == 0) {
                        this._tmpVelcity = v
                    } else {
                        if (!this._tmpVelcity) {
                            this._tmpVelcity = v
                        } else {
                            if (Math.abs(Math.atan2(this._tmpVelcity.x, this._tmpVelcity.y) - Math.atan2(v.x, v.y)) > 0.01) {
                                this._tmpVelcity = NewVec2(0, 0)
                                this.body.SetPosition(this._targetPos)
                            }
                        }
                    }
                }
                this.body.SetLinearVelocity(this._tmpVelcity)
                this.body.SetAwake(true)
                if (this._tmpVelcity.x == 0 && this._tmpVelcity.y == 0) {
                    this._needUpdate = false
                }
                return
            }
        }
        public afterStep() {
            if (this.isTap) {
                this._body.SetAwake(false)
            }
        }
    }
}